<script setup lang="ts">
import { fetchMobileBookAPI } from '@/apis/fetchMobileBook'
import { fetchStaffGroupAPI } from '@/apis/fetchStaffGroup'
import { fetchStaffListAPI } from '@/apis/fetchStaffList'
import { useUserInfoStore } from '@/store/userInfo'

const userInfoStore = useUserInfoStore()

const loading = ref(true)

const userGroupList = ref<StaffGroup[]>([])
const selectedTabIndex = ref(0)
const staffList = ref<(Staff | Person)[]>([])

watch(selectedTabIndex, (newVal) => {
  if (newVal >= userGroupList.value.length) {
    // 选中其他
    loadPersonList()
  }
  else {
    // 选中员工
    const selectedUserGroup = userGroupList.value[newVal]
    loadContacts(selectedUserGroup)
  }
})

const tabConfiguration = computed(() => {
  const tabs = userGroupList.value.map(userGroup => ({ name: userGroup.name }))
  tabs.push({ name: '其他' })
  return tabs
})

function getGroupById(groupId?: number) {
  if (userGroupList.value.filter(group => group.id === groupId).length > 0)
    return userGroupList.value.filter(group => group.id === groupId)[0]
}

function getPersonInfo(person: Person | Staff) {
  if ((person as any).group_id !== undefined) {
    return {
      avatar: (person as Staff).avatar,
      name: (person as Staff).nickname,
      phoneNumber: (person as Staff).mobile,
      identity: getGroupById((person as any).group_id)?.name,
    }
  }
  else {
    return {
      avatar: undefined,
      name: (person as Person).name,
      phoneNumber: (person as Person).mobile,
      identity: (person as Person).profession,
    }
  }
}

onMounted(async () => {
  try {
    const res = await fetchStaffGroupAPI()
    userGroupList.value = (res.data as any).data as StaffGroup[]
    await loadContacts(userGroupList.value[selectedTabIndex.value])
    loading.value = false
  }
  catch (err) {
    loading.value = false
    uni.showToast({ title: '获取数据失败', icon: 'none' })
  }
})

function handleTabChange(e: any) {
  selectedTabIndex.value = e.index
}

async function loadContacts(userGroup: StaffGroup, keyword?: string) {
  const groupId = userGroup.id
  if (groupId) {
    const res = await fetchStaffListAPI({ group_id: `${groupId}`, keyword }, userInfoStore.userInfo!.token!)
    if ((res.data as any).code === 1)
      staffList.value = (res.data as any).data as Staff[]
    else
      uni.showToast({ title: '获取数据失败，请稍后重试', icon: 'none' })
  }
}

async function loadPersonList(keyword?: string) {
  const res = await fetchMobileBookAPI(userInfoStore.userInfo!.token!, keyword)
  staffList.value = (res.data as any).data as Person[]
}

const handleSearch = useThrottleFn((keyword: string) => {
  if (selectedTabIndex.value >= userGroupList.value.length) {
    // 选中其他
    loadPersonList(keyword)
  }
  else {
    // 选中员工
    const selectedUserGroup = userGroupList.value[selectedTabIndex.value]
    loadContacts(selectedUserGroup, keyword)
  }
})
</script>

<template>
  <view class="flex flex-col min-h-screen bg-#F8F8F8">
    <view class="bg-white">
      <Spacer height="30" />
      <view class="mx-30rpx border-1px border-solid border-#E3E3E3 rounded-6rpx">
        <uv-search
          shape="square" bg-color="#F8F9FD" border-color="#E3E3E3" color="#000000" search-icon-size="36rpx"
          search-icon-color="#FF6D0A" placeholder-color="#999999" :show-action="false"
          height="74rpx" placeholder="请输入员工姓名/手机号" @change="handleSearch"
        />
      </view>
      <uv-tabs
        :list="tabConfiguration" line-color="#FF6D0A" line-width="48rpx" :active-style="{ color: '#000000', fontSize: '32rpx', lineHeight: '32rpx' }"
        :inactive-style="{ color: '#999999', fontSize: '28rpx', lineHeight: '28rpx' }"
        :custom-style="{ margin: '0 10rpx' }"
        @change="handleTabChange"
      />
    </view>
    <uv-list v-if="staffList.length > 0" :custom-style="{ padding: '30rpx 0', backgroundColor: '#F8F8F8' }">
      <uv-list-item v-for="person, index in staffList" :key="index" :custom-style="{ borderRadius: '20rpx' }">
        <PersonItem
          :avatar="person.avatar || 'http://jzt.tykhrs.cn/uploads/20240204/87b5977293b9856b96b77b21dcfc3e2a.png'"
          :name="getPersonInfo(person).name || '未知'" :identity="getPersonInfo(person).identity || '未知'"
          :phone-number="person.mobile || '未知'" :is-call-on-tap="true"
        />
        <Divider />
      </uv-list-item>
    </uv-list>
    <PageDefault v-else />
    <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
  </view>
</template>

<route lang="yaml">
name: 'managerContacts'
style:
  navigationBarTitleText: '通讯录'
layout: 'custom'
</route>
